'use client';

import { useSearchParams } from "next/navigation";
import { getQuestion } from "@/app/question/query";
import { useEffect, useState } from "react";
import { Simulate } from "react-dom/test-utils";

type question = {
    id: number
    desc: string
    // 选择题 填空题 选词填空 翻译 阅读 听力
    type: "choose" | "fill" | "multi-fill" | "word-fill" | "translate" | "read" | "learn" | "text-fill"
    // 选择题是数字 翻译是句子 填空是多个数字
    answer: number | string | []
    // 阅读题有文本
    content: string
    options: [],
    // 阅读 听力 有子题
    subs: {
        id: number
        desc: string
        type: "choose" | "fill" | "multi-fill" | "word-fill" | "translate" | "read" | "learn" | "text-fill"
        answer: number | string | []
        options: []
    }[],
    // 听力资源的路径
    path: string
}
type options = {
    id: number
    desc: string
}
type answer = {
    qid: number
    oid: number
    sid: number // 子题id
    input: any
    type: "choose" | "fill" | "multi-fill" | "word-fill" | "translate" | "read" | "learn" | "text-fill"
    real: number | string | []
}

export default function QuestionPage() {
    const searchParams = useSearchParams();
    console.log()
    let q = searchParams.get('q')
    let c = searchParams.get('c')
    if (!q || !c) return (
        <div>error</div>
    )

    // 题库
    const [data, setData] = useState<question[]>([])
    useEffect(() => {
        (async () => {
            let data = await getQuestion(c, q)
            console.log(JSON.parse(data.data))
            let qs = JSON.parse(data.data)
            setData(qs.qs)
        })()
        console.log(1)
    }, [])

    // 考生选择的答案
    const [answer, setAnswer] = useState<answer[]>([])
    const [point, setPoint] = useState(0) // 分数
    // 是否显示答案
    const [show, setShow] = useState(false)

    // @ts-ignore
    const submit = (e) => {
        e.preventDefault()
        console.log(answer)
        let realCnt = 0
        answer.forEach((a) => {
            if (a.type === 'choose') {
                console.log(a)
                if (a.oid === a.real) {
                    realCnt++
                }
            }
            if (a.type === 'word-fill') {
                let cnt = 0
                for (let i = 0; i < a.input.length; i++) {
                    // @ts-ignore
                    if (a.input[i] === a.real[i]) {
                        cnt++
                    }
                }
                // @ts-ignore
                if (cnt === a.real.length) realCnt++
            }
            if (a.type === 'translate') {
                if (a.input === a.real) realCnt++
            }
            if (a.type === 'fill') {
                console.log(a.input, a.real)
                // @ts-ignore
                if (a.input.toLowerCase() === a.real.toLowerCase()) realCnt++
            }
            if (a.type === 'multi-fill') {
                console.log(a.input, a.real)
                let inputs = a.input.split(',')
                console.log(inputs)
                let cnt = 0
                for (let i = 0; i < inputs.length; i++) {
                    // @ts-ignore
                    if (inputs[i] === a.real[i]) {
                        cnt++
                    }
                }
                // @ts-ignore
                if (cnt === a.real.length) realCnt++
            }
        })

        let len = 0
        data.forEach((d) => {
            if (d.subs && d.subs.length > 0) {
                len += d.subs.length
                return;
            }
            len += 1
            return
        })
        // @ts-ignore
        setPoint((realCnt / len).toFixed(1) * 100)
        window.scrollTo(0, 0)
        alert(`答对${realCnt}道`)
    }

    const change = (q: question, o: options | undefined, customUserAnswer: any) => {
        // if (q.type === 'learn' || q.type === 'read') {
        //     // 根据子题分配唯一id
        //     q.id = q.id + 114514 + customUserAnswer.id
        // }
        console.log(answer)
        // @ts-ignore
        let old = answer.filter(a =>
            a.qid === q.id
        )
        let idx = answer.indexOf(old[0])

        if (old.length <= 0 || idx === -1) {
            setAnswer([...answer, {
                qid: q.id,
                oid: o?.id || -1,
                sid: customUserAnswer?.id || -1,
                input: customUserAnswer,
                real: q.answer,
                type: q.type
            }])
            return
        }
        let newAns = answer.map((a, i) => {
            if (i == idx) {
                return {
                    qid: q.id,
                    oid: o?.id || -1,
                    sid: customUserAnswer?.id || -1,
                    input: customUserAnswer,
                    real: q.answer,
                    type: q.type
                }
            }
            return a
        })
        setAnswer(newAns)
    }

    // 乱序方法
    function randomArr(arr: []) {
        var len = arr.length;
        //首先从最大的数开始遍历，之后递减
        for (var i = len - 1; i >= 0; i--) {
            var randomIndex = Math.floor(Math.random() * (i + 1));  //随机索引值randomIndex是从0-arr.length中随机抽取的，因为Math.floor()方法是向下取整的，所以这里是i+1
            //下面三句相当于把从数组中随机抽取到的值与当前遍历的值互换位置
            var temp = arr[randomIndex];
            arr[randomIndex] = arr[i];
            arr[i] = temp;
        }
        //每一次的遍历都相当于把从数组中随机抽取（不重复）的一个元素放到数组的最后面
        return arr;
    }

    return (
        <div className={'font-mono flex flex-col items-center gap-4 my-4'}>
            <div className={'w-[780px] text-center text-xl p-2 rounded-lg shadow-md bg-neutral-300'}>{c} {q}</div>
            <div className={'w-[780px] text-center text-xl p-2 rounded-lg shadow-md bg-amber-300'}>分数 {point}</div>
            <form onSubmit={submit} className={'font-mono flex items-center flex-col gap-4'}>
                {data.map((q) => (
                    <div className={'shadow-md w-[780px] bg-sky-50 p-2 rounded-lg'}>
                        <span className={'my-2 text-lg'}>{q.desc}</span>
                        {show && (
                            <div className={'text-rose-500 mt-1 font-bold'}
                                dangerouslySetInnerHTML={{ __html: `答案：${q.answer}` }}>
                                {/*答案: {q.type === 'read' || 'learn' ?*/}
                                {/*(<span>{JSON.stringify(q.answer)}</span>) : (*/}
                                {/*    <span>{q.answer}</span>*/}
                                {/*)}*/}
                            </div>
                        )}
                        {/*choose选择题*/}
                        {q.type === 'choose' && (
                            <>
                                <div className={'my-2 border-2 border-lime-600 rounded-lg p-2'}>
                                    {/*todo*/}
                                    {(q.options).map((o: options, index: number) => (
                                        <div className={`my-2 border-2 border-lime-600 rounded-lg p-2 ${show && q.answer === o.id
                                                ? 'bg-green-300' : ''}`}>
                                            <input
                                                onChange={(e) => change(q, o, undefined)}
                                                type={'radio'} id={q.id + o.desc} name={q.desc}
                                                value={o.id} />
                                            <label htmlFor={q.desc + q.id + o.id + o.desc}
                                                className={'p-2'}>{o.desc}</label>
                                        </div>
                                    ))}
                                </div>
                            </>
                        )}
                        {/*word-fill选词填空*/}
                        {q.type === 'word-fill' && (
                            <>
                                <div className={'flex flex-row flex-wrap gap-2 my-2'}>
                                    {/*todo*/}
                                    {(q.options).map((o: options) => (
                                        <span
                                            key={o.id} className={'p-1 rounded-lg '}>
                                            {o.id}. {o.desc}
                                        </span>
                                    ))}
                                </div>
                                <div dangerouslySetInnerHTML={{ __html: q.content }}>
                                </div>
                                <input 
                                    type="text"
                                    className={'w-full rounded-lg p-1'}
                                    placeholder={'请输入数字序列, 用逗号隔开'}
                                    onChange={(e) => {
                                        let val = e.target.value
                                        let inputs = val.split(',')
                                        change(q, undefined, inputs)
                                    }} />
                            </>
                        )}
                        {/*翻译题translate*/}
                        {q.type === 'translate' && (
                            <>
                                <div className={'flex flex-col gap-2'}>
                                    <input
                                        onChange={(e) => {
                                            change(q, undefined, e.target.value)
                                        }}
                                        type="text" className={'mt-2 rounded-lg p-1'} placeholder={'输入翻译'} />
                                </div>
                            </>
                        )}
                        {q.type === 'learn' && (
                            <div className={'my-2'}>
                                <audio src={q.path} controls>
                                    浏览器不支持音频播放。
                                </audio>
                                <div className={'my-2 border-2 border-lime-600 rounded-lg p-2'}
                                    dangerouslySetInnerHTML={{ __html: q.content }}
                                ></div>
                                {q.subs.map((s) => (
                                    <div className={'border-2 border-lime-600 rounded-lg mt-2 flex flex-col'}>
                                        <span className={'p-2'}>{s.desc}</span>
                                        {/*todo*/}
                                        {(s.options).map((o: options, index: number) => (
                                            <div
                                                className={`flex flex-row rounded-lg p-2 ${show && s.answer === o.id
                                                        ? 'bg-green-300' : ''} gap-2`}>
                                                <input
                                                    className={''}
                                                    onChange={(e) =>
                                                        change(s as question, o, undefined)}
                                                    type={'radio'} id={s.id + o.desc} name={s.desc || s.id.toString()}
                                                    value={s.id + o.id} />
                                                <label htmlFor={s.id + o.desc}>{index + '. ' + o.desc}</label>
                                            </div>
                                        ))}
                                    </div>
                                ))}
                            </div>
                        )}
                        {q.type === 'read' && (
                            <div className={'my-2'}>
                                <div className={'border-2 rounded-lg p-2 border-amber-200'}
                                    dangerouslySetInnerHTML={{ __html: q.content }}>
                                </div>
                                {q.subs.map((s) => (
                                    <div className={'mt-2 flex flex-col'}>
                                        <span>{s.desc}</span>
                                        {/*todo*/}
                                        {s.type === 'choose' && (s.options).map((o: options) => (
                                            <div className={`flex flex-row rounded-lg p-2 ${show && s.answer === o.id
                                                    ? 'bg-green-300' : ''
                                                } gap-2 `}>
                                                <input
                                                    className={''}
                                                    onChange={(e) =>
                                                        change(s as question, o, undefined)}
                                                    type={'radio'} id={s.id + o.desc} name={s.desc}
                                                    value={o.id} />
                                                <label htmlFor={s.id + o.desc}>{o.desc}</label>
                                            </div>
                                        ))}
                                        {s.type === 'fill' && (
                                            <>
                                                <div className={'flex flex-col gap-1'}>
                                                    {show && <span
                                                        className={'bg-green-300 rounded-lg p-1 mt-2'}>{s.answer}</span>}
                                                    <input
                                                        onChange={(e) => {
                                                            change(s as question, undefined, e.target.value)
                                                        }}
                                                        type="text" className={'mt-2 rounded-lg p-1'}
                                                        placeholder={'输入'} />
                                                </div>
                                            </>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )}
                        {q.type === 'fill' && (
                            <>
                                <div className={'flex flex-col gap-1'}>
                                    {show && <span
                                        className={'bg-green-300 rounded-lg p-1 mt-2'}>{q.answer}</span>}
                                    <input
                                        onChange={(e) => {
                                            change(q, undefined, e.target.value)
                                        }}
                                        type="text" className={'mt-2 rounded-lg p-1'}
                                        placeholder={'输入'} />
                                </div>
                            </>
                        )}
                        {q.type === 'text-fill' && (
                            <>
                                <div className={'flex flex-col gap-1'}>
                                    {/*{show && <div dangerouslySetInnerHTML={{__html: q.answer}}></div>}*/}
                                    <textarea
                                        onChange={(e) => {
                                            change(q, undefined, e.target.value)
                                        }} className={'mt-2 rounded-lg p-1'}
                                        placeholder={'输入'} />
                                </div>
                            </>
                        )}
                        {q.type === 'multi-fill' && (
                            <>
                                <div className={'flex flex-col gap-1'}>
                                    {show && <span
                                        className={'bg-green-300 rounded-lg p-1 mt-2'}>{q.answer}</span>}
                                    <input
                                        onChange={(e) => {
                                            change(q, undefined, e.target.value)
                                        }}
                                        type="text" className={'mt-2 rounded-lg p-1'}
                                        placeholder={'输入'} />
                                </div>
                            </>
                        )}
                    </div>
                )
                )}
                <div className={'flex flex-row gap-4'}>
                    <button className={'shadow-md p-2 text-lg bg-green-200 rounded-lg w-24'} type={'submit'}>提交
                    </button>
                    <button onClick={() => setShow(!show)} type={'button'}
                        className={'shadow-md p-2 text-lg bg-green-200 rounded-lg w-24'}>
                        {show ? "隐藏答案" : "显示答案"}
                    </button>
                </div>
            </form>
        </div>
    )
}